import { useEffect, useRef, useState, RefObject } from 'react';

function useResizeObserver<T extends HTMLElement>(
    dom: T,
    onResize: (size: DOMRectReadOnly) => void
): void {
    const observed = useRef<ResizeObserver | null>(null);

    useEffect(() => {
        const observer = new ResizeObserver(([entry]) => {
            console.log(entry);

            onResize(entry.contentRect);
        });

        if (dom) {
            observer.observe(dom);
            observed.current = observer;
        }

        return () => {
            if (observed.current) {
                observed.current.unobserve(dom!);
                observed.current = null;
            }
        };
    }, [dom, onResize]);
}

export default useResizeObserver;